package com.wudl.db.config;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
import java.util.HashMap;
import java.util.Map;
/**
 * @ClassName : DataSourceConfig
 * @Description :
 * @Author :wudl
 * @Date: 2021-08-06 00:01
 */

@Configuration
@MapperScan(basePackages = {"com.wudl.db.mapper"},sqlSessionFactoryRef = "sqlSessionFactoryBean")
public class DataSourceConfig {
    @Value("${master.datasource.driver-class-name}")
    private String masterDriverClassName;
    @Value("${master.datasource.url}")
    private String masterUrl;
    @Value("${master.datasource.username}")
    private String masterUsername;
    @Value("${master.datasource.password}")
    private String masterPassword;

    @Value("${slave.datasource.driver-class-name}")
    private String slaveDriverClassName;
    @Value("${slave.datasource.url}")
    private String slaveUrl;
    @Value("${slave.datasource.username}")
    private String slaveUsername;
    @Value("${slave.datasource.password}")
    private String slavePassword;


    @Bean
    public DruidDataSource masterDruidDataSource(){
        DruidDataSource druidDataSource=new DruidDataSource();
        druidDataSource.setDriverClassName(masterDriverClassName);
        druidDataSource.setUrl(masterUrl);
        druidDataSource.setUsername(masterUsername);
        druidDataSource.setPassword(masterPassword);
        return druidDataSource;
    }

    @Bean
    public DruidDataSource salveDruidDataSource(){
        DruidDataSource druidDataSource=new DruidDataSource();
        druidDataSource.setDriverClassName(slaveDriverClassName);
        druidDataSource.setUrl(slaveUrl);
        druidDataSource.setUsername(slaveUsername);
        druidDataSource.setPassword(slavePassword);
        return druidDataSource;
    }
    @Bean
    public MyDataSource myDataSource(DruidDataSource masterDruidDataSource,DruidDataSource salveDruidDataSource){
        MyDataSource myDataSource=new MyDataSource();
        myDataSource.setDefaultTargetDataSource(masterDruidDataSource);
        Map dataSourceMap=new HashMap();
        dataSourceMap.put("master",masterDruidDataSource);
        dataSourceMap.put("slave",salveDruidDataSource);
        myDataSource.setTargetDataSources(dataSourceMap);
        return myDataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(MyDataSource myDataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(myDataSource);
        return sqlSessionFactoryBean;
    }

}
